import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { setToken, setCurrentUser, debugAuth } from '../utils/auth';

const Login = () => {
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const handleLogin = async (values) => {
        try {
            setLoading(true);
            console.log('发送登录请求:', values);

            const response = await fetch('http://localhost:8080/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(values),
            });

            const data = await response.json();
            console.log('收到响应:', response.status, data);

            if (response.ok && data.accessToken) {
                console.log('登录成功，准备存储 token');

                // 存储 token
                setToken(data.accessToken);

                // 存储用户信息
                const userInfo = {
                    username: data.username,
                    email: data.email
                };
                setCurrentUser(userInfo);

                // 验证存储是否成功
                setTimeout(() => {
                    const storedToken = localStorage.getItem('token');
                    console.log('存储验证:', storedToken ? '成功' : '失败');
                    debugAuth();

                    // 确保 token 存储后再导航
                    if (storedToken) {
                        message.success('登录成功！');
                        navigate('/dashboard', { replace: true });
                    } else {
                        message.error('Token 存储失败');
                    }
                }, 200);

            } else {
                console.error('登录失败:', data);
                message.error(data.message || '登录失败');
            }
        } catch (error) {
            console.error('登录错误:', error);
            message.error('网络错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            minHeight: '100vh',
            background: '#f0f2f5'
        }}>
            <Card title="用户登录" style={{ width: 400 }}>
                <Form
                    name="login"
                    onFinish={handleLogin}
                    autoComplete="off"
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                        <Input
                            prefix={<UserOutlined />}
                            placeholder="用户名"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password
                            prefix={<LockOutlined />}
                            placeholder="密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                            size="large"
                            style={{ width: '100%' }}
                        >
                            登录
                        </Button>
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="link"
                            onClick={() => navigate('/register')}
                            style={{ width: '100%' }}
                        >
                            还没有账号？立即注册
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
};

export default Login;
